package com.kkb.controller;

import com.kkb.entity.Result;
import com.kkb.utils.SMSUtils;
import com.kkb.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Author likepei
 * @Date 2020/6/17 15:07
 * @Version v1.0
 * @Description 验证码
 */

@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送验证码 (用户登录操作)
     * @param telephone 手机号码
     * @return
     */
    @PostMapping("/send4Login/{telephone}")
    public Result send4Login(@PathVariable("telephone") String telephone){
        try {
            //生成短信验证码
            String validateCode = ValidateCodeUtils.generateValidateCode4String(6);

            System.out.println(telephone + "生成短信验证码validateCode = " + validateCode);

            //调用阿里云的发送短信的服务
            SMSUtils.sendShortMessage(telephone, validateCode);

            //验证码存入Redis, 加入过期时间, 用于后期的验证码对比
            stringRedisTemplate.boundValueOps("member.validateCode").set(validateCode);

            //发送短信验证码成功, 返回成功信息
            return new Result(true, "验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            //发送短信验证码失败, 返回失败信息
            return new Result(false,"验证码发送失败");
        }
    }
}
